package com.mnb.beidou.utils;

public class ByteUtils {
    /**
     * 十六进制字符串转字节数组
     */
    public static byte[] hexStringToByteArray(String s) {
        if (s == null || s.isEmpty()) {
            return new byte[0];
        }

        int len = s.length();
        // 确保字符串长度为偶数
        if (len % 2 != 0) {
            System.out.println("警告：十六进制字符串长度为奇数，自动补全最后一位");
            s += "0";
            len++;
        }

        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    /**
     * 字节数组转十六进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }

    /**
     * BCD码转十进制字符串
     *
     * @param bcd                  BCD字节数组
     * @param preserveLeadingZeros 是否保留前导零
     */
    public static String bcdToDecimal(byte[] bcd, boolean preserveLeadingZeros) {
        if (bcd == null || bcd.length == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : bcd) {
            int high = (b & 0xF0) >> 4; // 高4位
            int low = b & 0x0F; // 低4位

            // 检查是否为有效的BCD码（0-9）
            if (high < 0 || high > 9 || low < 0 || low > 9) {
                System.out.println("警告：检测到无效的BCD码字节 0x" + String.format("%02X", b));
            }

            sb.append(high);
            sb.append(low);
        }

        if (preserveLeadingZeros) {
            return sb.toString();
        } else {
            String result = sb.toString().replaceAll("^0+", "");
            return result.isEmpty() ? "0" : result;
        }
    }
}
